{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "o_0K1lsW1dj9"
   },
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
    "\n",
    "Instructions for setting up Colab are as follows:\n",
    "1. Open a new Python 3 notebook.\n",
    "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
    "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
    "4. Run this cell to set up dependencies.\n",
    "\"\"\"\n",
    "# If you're using Google Colab and not running locally, run this cell\n",
    "\n",
    "# install NeMo\n",
    "BRANCH = 'main'\n",
    "!python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[nlp]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "JFWG-jYCfvD7",
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "# If you're not using Colab, you might need to upgrade jupyter notebook to avoid the following error:\n",
    "# 'ImportError: IProgress not found. Please update jupyter and ipywidgets.'\n",
    "\n",
    "! pip install ipywidgets\n",
    "! jupyter nbextension enable --py widgetsnbextension\n",
    "\n",
    "# Please restart the kernel after running this cell"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "dzqD2WDFOIN-"
   },
   "outputs": [],
   "source": [
    "import json\n",
    "import os\n",
    "\n",
    "from nemo.collections import nlp as nemo_nlp\n",
    "from nemo.utils.exp_manager import exp_manager\n",
    "from nemo.utils import logging\n",
    "from omegaconf import OmegaConf\n",
    "import pandas as pd\n",
    "import pytorch_lightning as pl\n",
    "import torch\n",
    "import wget "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "daYw_Xll2ZR9"
   },
   "source": [
    "# Task description\n",
    "\n",
    "Intent recognition is the task of classifying the intent of an utterance or document. For example,  for the query:  `What is the weather in Santa Clara tomorrow morning?`, we would like to classify the intent as `weather`. This is a fundamental step that is executed in any task-driven conversational assistant.\n",
    "\n",
    "Typical text classification models, such as the Joint Intent and Slot Classification Model in NeMo, are trained on hundreds or thousands of labeled documents. In this tutorial we demonstrate a different, \"zero shot\" approach that requires no annotated data for the target intents. The zero shot approach uses a model trained on the task of natural language inference (NLI). During training, the model is presented with pairs of sentences consisting of a \"premise\" and a \"hypothesis\", and must classify the relationship between them as entailment (meaning the hypothesis follows logically from the premise), contradiction, or neutral. To use this model for intent prediction, we define a list of candidate labels to represent each of the possible classes in our classification system; for example, the candidate labels might be `request for directions`,  `query about weather`, `request to play music`, etc. We predict the intent of a query by pairing it with each of the candidate labels as a premise-hypothesis pair and using the model to predict the probability of an entailment relationship between them. For example, for the query and candidate labels above, we would run inference for the following pairs:\n",
    "\n",
    "(`What is the weather in Santa Clara tomorrow morning?`, `request for directions`)  \n",
    "(`What is the weather in Santa Clara tomorrow morning?`, `request to play music`)   \n",
    "(`What is the weather in Santa Clara tomorrow morning?`, `query about weather`)\n",
    "\n",
    "In the above example, we would expect a high probability of entailment for the last pair, and low probabilities for the first two pairs. Thus, we would classify the intent of the utterance as `query about weather`. The task can be formulated as single-label classification (only one of the candidate labels can be correct for each query) or multi-label classification (multiple labels can be correct) by setting the parameter multi_label = False or multi_label = True, respectively, during inference.\n",
    "\n",
    "In this tutorial, we demonstrate how to train an NLI model on the MNLI data set and how to use it for zero shot intent recognition."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Using an out-of-the-box model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# this line will download a pre-trained NLI model from NVIDIA's NGC cloud and instantiate it for you\n",
    "\n",
    "pretrained_model = nemo_nlp.models.ZeroShotIntentModel.from_pretrained(\"zeroshotintent_en_bert_base_uncased\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "queries = [\n",
    "    \"What is the weather in Santa Clara tomorrow morning?\",\n",
    "    \"I'd like a veggie burger and fries\",\n",
    "    \"Bring me some ice cream when it's sunny\"\n",
    "\n",
    "]\n",
    "\n",
    "candidate_labels = ['Food order', 'Weather query', \"Play music\"]\n",
    "\n",
    "predictions = pretrained_model.predict(queries, candidate_labels, batch_size=4, multi_label=True)\n",
    "\n",
    "print('The prediction results of some sample queries with the trained model:')\n",
    "for query in predictions:\n",
    "    print(json.dumps(query, indent=4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the example above, we set `multi_label=True`, which is also the default setting. This runs a softmax calculation independently for each label over the entailment and contradiction logits. For any given query, the scores for the different labels may add up to more than one.\n",
    "\n",
    "Below, we see what happens if we set `multi_label=False`. In this case, the softmax calculation for each query uses the entailment class logits for all the labels, so the final scores for all classes add up to one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictions = pretrained_model.predict(queries, candidate_labels, batch_size=4, multi_label=False)\n",
    "\n",
    "print('The prediction results of some sample queries with the trained model:')\n",
    "for query in predictions:\n",
    "    print(json.dumps(query, indent=4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Under the hood, during inference the candidate labels are not used as is; they're actually used to fill in the blank in a hypothesis template. By default, the hypothesis template is `This example is {}`. So the candidate labels above would actually be presented to the model as `This example is food order`, `This example is weather query`, and `This example is play music`. You can change the hypothesis template with the optional keyword argument `hypothesis_template`, as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictions = pretrained_model.predict(queries, candidate_labels, batch_size=4, multi_label=False,\n",
    "                                      hypothesis_template=\"a person is asking something related to {}\")\n",
    "\n",
    "print('The prediction results of some sample queries with the trained model:')\n",
    "for query in predictions:\n",
    "    print(json.dumps(query, indent=4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ZnuziSwJ1yEB"
   },
   "source": [
    "Now, let's take a closer look at the model's configuration and learn to train the model.\n",
    "\n",
    "\n",
    "# Training your own model\n",
    "\n",
    "\n",
    "# Dataset\n",
    "\n",
    "In this tutorial we will train a model on [The Multi-Genre Natural Language Inference Corpus](https://cims.nyu.edu/~sbowman/multinli/multinli_0.9.pdf) (MNLI). This is a crowdsourced collection of sentence pairs with textual entailment annotations. Given a premise sentence followed by a hypothesis sentence, the task is to predict whether the premise entails the hypothesis (entailment), contradicts the hypothesis (contradiction), or neither (neutral). There are two dev sets for this task: the \"matched\" dev set contains examples drawn from the same genres as the training set, and the \"mismatched\" dev set has examples from genres not seen during training. For our purposes, either dev set alone will be sufficient. We will use the \"matched\" dev set here. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Download the dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "--wJ2891aIIE"
   },
   "outputs": [],
   "source": [
    "# you can replace DATA_DIR with your own location\n",
    "DATA_DIR = '.'  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "wget.download('https://dl.fbaipublicfiles.com/glue/data/MNLI.zip', DATA_DIR)\n",
    "! unzip {DATA_DIR}/MNLI.zip -d {DATA_DIR}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "qB0oLE4R9EhJ"
   },
   "outputs": [],
   "source": [
    "! ls -l $DATA_DIR/MNLI"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "gMWuU69pbUDe"
   },
   "source": [
    "We will use `train.tsv` as our training set and `dev_matched.tsv` as our validation set."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Explore the dataset  \n",
    "Let's take a look at some examples from the dev set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_examples = 5\n",
    "df = pd.read_csv(os.path.join(DATA_DIR, \"MNLI\", \"dev_matched.tsv\"), sep=\"\\t\")[:num_examples]\n",
    "for sent1, sent2, label in zip(df['sentence1'].tolist(), df['sentence2'].tolist(), df['gold_label'].tolist()):\n",
    "    print(\"sentence 1: \", sent1)\n",
    "    print(\"sentence 2: \", sent2)\n",
    "    print(\"label: \", label)\n",
    "    print(\"===================\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "_whKCxfTMo6Y"
   },
   "source": [
    "# Training model\n",
    "## Model configuration\n",
    "\n",
    "The model is comprised of the pretrained [BERT](https://arxiv.org/pdf/1810.04805.pdf) model followed by a Sequence Classifier module.\n",
    "\n",
    "The model is defined in a config file which declares multiple important sections. They are:\n",
    "- **model**: All arguments that are related to the Model - language model, a classifier, optimizer and schedulers, datasets and any other related information\n",
    "\n",
    "- **trainer**: Any argument to be passed to PyTorch Lightning\n",
    "\n",
    "All model and training parameters are defined in the **zero_shot_intent_config.yaml** config file. This file is located in the folder **examples/nlp/zero_shot_intent_recognition/conf/**. It contains 2 main sections:\n",
    "\n",
    "\n",
    "We will download the config file from the repository for the purpose of the tutorial. If you have a version of NeMo installed locally, you can use it from the above folder."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "T1gA8PsJ13MJ"
   },
   "outputs": [],
   "source": [
    "# download the model config file from repository for the purpose of this example\n",
    "WORK_DIR = \".\"  # you can replace WORK_DIR with your own location\n",
    "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/zero_shot_intent_recognition/conf/zero_shot_intent_config.yaml', WORK_DIR)\n",
    "\n",
    "# print content of the config file\n",
    "config_file = os.path.join(WORK_DIR, \"zero_shot_intent_config.yaml\")\n",
    "config = OmegaConf.load(config_file)\n",
    "print(OmegaConf.to_yaml(config))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ZCgWzNBkaQLZ"
   },
   "source": [
    "## Setting up data within the config\n",
    "\n",
    "Among other things, the config file contains dictionaries called **dataset**, **train_ds** and **validation_ds**. These are configurations used to setup the Dataset and DataLoaders of the corresponding config.\n",
    "\n",
    "To start model training, we need to specify `model.dataset.data_dir`, `model.train_ds.file_name` and `model.validation_ds.file_name`, as we are going to do below.\n",
    "\n",
    "Notice that some config lines, including `model.train_ds.data_dir`, have `???` in place of paths. This means that values for these fields are required to be specified by the user.\n",
    "\n",
    "Let's now add the data paths and output directory for saving predictions to the config."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "LQHCJN-ZaoLp"
   },
   "outputs": [],
   "source": [
    "# you can replace OUTPUT_DIR with your own location; this is where logs and model checkpoints will be saved\n",
    "OUTPUT_DIR = \"nemo_output\"\n",
    "config.exp_manager.exp_dir = OUTPUT_DIR\n",
    "config.model.dataset.data_dir = os.path.join(DATA_DIR, \"MNLI\")\n",
    "config.model.train_ds.file_name = \"train.tsv\"\n",
    "config.model.validation_ds.file_path = \"dev_matched.tsv\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "nB96-3sTc3yk"
   },
   "source": [
    "## Building the PyTorch Lightning Trainer\n",
    "\n",
    "NeMo models are primarily PyTorch Lightning modules - and therefore are entirely compatible with the PyTorch Lightning ecosystem.\n",
    "\n",
    "Let's first instantiate a Trainer object"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "1tG4FzZ4Ui60"
   },
   "outputs": [],
   "source": [
    "print(\"Trainer config - \\n\")\n",
    "print(OmegaConf.to_yaml(config.trainer))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "knF6QeQQdMrH"
   },
   "outputs": [],
   "source": [
    "# lets modify some trainer configs\n",
    "# checks if we have GPU available and uses it\n",
    "cuda = 1 if torch.cuda.is_available() else 0\n",
    "config.trainer.gpus = cuda\n",
    "\n",
    "config.trainer.precision = 16 if torch.cuda.is_available() else 32\n",
    "\n",
    "# for mixed precision training, uncomment the line below (precision should be set to 16 and amp_level to O1):\n",
    "# config.trainer.amp_level = O1\n",
    "\n",
    "# remove distributed training flags\n",
    "config.trainer.accelerator = None\n",
    "\n",
    "# setup max number of steps to reduce training time for demonstration purposes of this tutorial\n",
    "config.trainer.max_steps = 128\n",
    "\n",
    "trainer = pl.Trainer(**config.trainer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "8IlEMdVxdr6p"
   },
   "source": [
    "## Setting up a NeMo Experiment\n",
    "\n",
    "NeMo has an experiment manager that handles logging and checkpointing for us, so let's use it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "8uztqGAmdrYt"
   },
   "outputs": [],
   "source": [
    "exp_dir = exp_manager(trainer, config.get(\"exp_manager\", None))\n",
    "\n",
    "# the exp_dir provides a path to the current experiment for easy access\n",
    "exp_dir = str(exp_dir)\n",
    "exp_dir"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "8tjLhUvL_o7_"
   },
   "source": [
    "Before initializing the model, we might want to modify some of the model configs. For example, we might want to modify the pretrained BERT model and use [Megatron-LM BERT](https://arxiv.org/abs/1909.08053) or [AlBERT model](https://arxiv.org/abs/1909.11942):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "Xeuc2i7Y_nP5"
   },
   "outputs": [],
   "source": [
    "# get the list of supported BERT-like models, for the complete list of HugginFace models, see https://huggingface.co/models\n",
    "print(nemo_nlp.modules.get_pretrained_lm_models_list(include_external=True))\n",
    "\n",
    "# specify BERT-like model, you want to use, for example, \"megatron-bert-345m-uncased\" or 'bert-base-uncased'\n",
    "PRETRAINED_BERT_MODEL = \"albert-base-v1\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "RK2xglXyAUOO"
   },
   "outputs": [],
   "source": [
    "# add the specified above model parameters to the config\n",
    "config.model.language_model.pretrained_model_name = PRETRAINED_BERT_MODEL"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "fzNZNAVRjDD-"
   },
   "source": [
    "Now, we are ready to initialize our model. During the model initialization call, the dataset and data loaders we'll be prepared for training and evaluation.\n",
    "Also, the pretrained BERT model will be downloaded, note it can take up to a few minutes depending on the size of the chosen BERT model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "NgsGLydWo-6-"
   },
   "outputs": [],
   "source": [
    "model = nemo_nlp.models.ZeroShotIntentModel(cfg=config.model, trainer=trainer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "kQ592Tx4pzyB"
   },
   "source": [
    "## Monitoring training progress\n",
    "Optionally, you can create a Tensorboard visualization to monitor training progress."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "mTJr16_pp0aS"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "  from google import colab\n",
    "  COLAB_ENV = True\n",
    "except (ImportError, ModuleNotFoundError):\n",
    "  COLAB_ENV = False\n",
    "\n",
    "# Load the TensorBoard notebook extension\n",
    "if COLAB_ENV:\n",
    "  %load_ext tensorboard\n",
    "  %tensorboard --logdir {exp_dir}\n",
    "else:\n",
    "  print(\"To use tensorboard, please use this notebook in a Google Colab environment.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "hUvnSpyjp0Dh"
   },
   "outputs": [],
   "source": [
    "# start model training\n",
    "trainer.fit(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Inference from Examples\n",
    "The next step is to see how the trained model will classify intents. To improve the predictions you may need to train the model for more than 5 epochs.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# reload the saved model\n",
    "saved_model = os.path.join(exp_dir, \"checkpoints/ZeroShotIntentRecognition.nemo\")\n",
    "eval_model = nemo_nlp.models.ZeroShotIntentModel.restore_from(saved_model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "queries = [\n",
    "    \"I'd like a veggie burger and fries\",\n",
    "    \"Turn off the lights in the living room\",\n",
    "]\n",
    "\n",
    "candidate_labels = ['Food order', 'Play music', 'Request for directions', 'Change lighting', 'Calendar query']\n",
    "\n",
    "predictions = eval_model.predict(queries, candidate_labels, batch_size=4, multi_label=True)\n",
    "\n",
    "print('The prediction results of some sample queries with the trained model:')\n",
    "for query in predictions:\n",
    "    print(json.dumps(query, indent=4))\n",
    "print(\"Inference finished!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As described above in \"Using an out of the box model\", you can set multi_label=False if you want the scores for each query to add up to one. You can also change the hypothesis template used when presenting candidate labels, as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictions = eval_model.predict(queries, candidate_labels, batch_size=4, multi_label=True,\n",
    "                           hypothesis_template=\"related to {}\")\n",
    "\n",
    "print('The prediction results of some sample queries with the trained model:')\n",
    "for query in predictions:\n",
    "    print(json.dumps(query, indent=4))\n",
    "print(\"Inference finished!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default, when an NLI model is trained on MNLI in NeMo, the class indices for entailment and contradiction are 1 and 0, respectively. The `predict` method uses these indices by default. If your NLI model was trained with different class indices for these classes, you can pass the correct indices as keyword arguments to the `predict` method (e.g. `entailment_idx=1`, `contradiction_idx=0`). "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ref1qSonGNhP"
   },
   "source": [
    "## Training Script\n",
    "\n",
    "If you have NeMo installed locally, you can also train the model with [examples/nlp/zero_shot_intent_recognition/zero_shot_intent_train.py](https://github.com/carolmanderson/NeMo/blob/main/examples/nlp/zero_shot_intent_recognition/zero_shot_intent_train.py).\n",
    "\n",
    "To run training script, use:\n",
    "\n",
    "```\n",
    "python zero_shot_intent_train.py \\\n",
    " model.dataset.data_dir=PATH_TO_DATA_FOLDER\n",
    "```\n",
    " \n",
    " By default, this script uses `examples/nlp/zero_shot_intent_recognition/conf/zero_shot_intent_config.yaml` config file, and you may update all the params inside of this config file or alternatively provide them in the command line.\n"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "GLUE_Benchmark.ipynb",
   "private_outputs": true,
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python [conda env:zeroshot_dev_2]",
   "language": "python",
   "name": "conda-env-zeroshot_dev_2-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
